package com.tsp_tux.demo.Controller;

import com.tsp_tux.demo.Entity.RespBean;
import com.tsp_tux.demo.Enum.PictureType;
import com.tsp_tux.demo.Service.ArticleService;
import com.tsp_tux.demo.Service.FileService;
import com.tsp_tux.demo.Util.SHA;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.tsp_tux.demo.Util.easyRespBean;
import com.tsp_tux.demo.Util.QiNiuPicture;

import javax.annotation.Resource;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 沈育洋
 */
//TODO：测试


@RestController
@CrossOrigin
public class UploadController {

    private static String filePath = "/home/tsp_tux/dist/file/";
    private static String baseUrl = "http://47.107.40.143:8081/file/";

    private static boolean createDir(String destDirName) {
        File dir = new File(filePath+destDirName);
        if (!dir.exists())
            if (dir.mkdirs())
                return true;
        return false;
    }
    @Resource
    FileService fileService;


    /**
     * 上传文件后保存至本地
     * 若是图片则上传至七牛云并返回其外链
     *
     * @param file MultipartFile 上传的文件
     * @return RespBean
     */
    @CrossOrigin
    @PostMapping(value = "upload")
    public RespBean upload(@RequestParam("file") MultipartFile file,Integer sid , Integer aid ,String uid) {
        if (file.isEmpty()) {
            return new RespBean(400, "请选择文件", null);
        }
        String fileName = file.getOriginalFilename();
        String [] fileSuffix = file.getContentType().split("/");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String key;
        //如果是图片则上传到七牛云并形成外链
        if (PictureType.isInclude(fileSuffix[1])) {
            byte[] uploadBytes;
            Map<String, String> map = new HashMap<>();
            //如果文件大小超过5M进行压缩
            if (file.getSize() >= 5 * 1024 * 1024) {
                try {
                    Thumbnails.of(file.getInputStream())
                            .scale(1f)
                            .outputQuality(0.5f)
                            .outputFormat("jpg")
                            .toOutputStream(outputStream);
                    uploadBytes = outputStream.toByteArray();
                    fileName = SHA.SHA256(outputStream);
                    map = QiNiuPicture.upload(fileName, uploadBytes);
                } catch (IOException | NoSuchAlgorithmException e) {
                    e.printStackTrace();
                    System.out.println("图片压缩失败");
                }
            } else {
                try {
                    uploadBytes = file.getBytes();
                    outputStream.write(uploadBytes);
                    fileName = SHA.SHA256(outputStream);
                    map = QiNiuPicture.upload(fileName, uploadBytes);
                } catch (IOException | NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
            if (map.containsKey("key")) {
                key = map.get("key");
                String outerChain = QiNiuPicture.outerChainBuild(key);
                int result = 0;
                if(aid !=-1||sid != -1)
                 result = fileService.upLoadFile(fileName,outerChain,fileSuffix[0],uid,aid,sid);
                if (outerChain == null||result !=0) {
                    return easyRespBean.err();
                }
                return easyRespBean.ok(outerChain);
            }
        } else {
            //非图片文件本地保存
            String url ;
            String path = uid+"/"+fileSuffix[0];
            try {
                if(sid!= -1)
                    path = "sid"+sid +"/" + path;
                if(aid!= -1)
                    path = "aid"+aid + "/" + path;
                createDir(path);
                url = baseUrl + path+"/"+ fileName;
                System.out.println(filePath+path +"/"+ fileName);
                File dest = new File(filePath+path +"/"+ fileName);
                file.transferTo(dest);
                int result = fileService.upLoadFile(fileName,url,fileSuffix[0],uid,aid,sid);
                if(result == 0)
                    return easyRespBean.ok(url);
                else
                    return easyRespBean.errWithMsg("上传失败");
            } catch (Exception e) {
                e.printStackTrace();
                return easyRespBean.errWithMsg("上传失败");
            }
        }

        return easyRespBean.errWithMsg("上传失败");
    }

    /**
     * Author 周志伟
     * @param rid
     * @return resBean
     */
     @PostMapping(value = "/deleteFiles")
    public RespBean deleteFile(Integer rid) {
        int result = fileService.deleteFileByRid(rid);
        if (result == 0) {
            return easyRespBean.okWithMsg("删除成功");
        }
        if(result == 2)
        return easyRespBean.okWithMsg("文件不存在！");
        return easyRespBean.okWithMsg("删除失败！");

    }
}
